package initialition

import (
	"didi-vehicle-certification/srv/global"
	"fmt"
	"github.com/go-redis/redis"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func init() {
	InitConfig()
	InitDB()
	InitRdb()
}

func InitConfig() {
	viper.SetConfigFile("./config/dev.yaml")
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
	viper.Unmarshal(&global.GlobalConfig)
	fmt.Println("解析配置", global.GlobalConfig)
}
func InitDB() {
	var err error
	config := global.GlobalConfig.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True", config.User, config.Password, config.Host, config.Port, config.Database)
	global.DB, err = gorm.Open(mysql.Open(dsn))
	if err != nil {
		panic(err)
	}
	fmt.Println("mysql connect")
}
func InitRdb() {

	global.Rdb = redis.NewClient(&redis.Options{
		Addr:     global.GlobalConfig.Redis.Host,
		Password: global.GlobalConfig.Redis.Password,
	})
	err := global.Rdb.Ping().Err()
	if err != nil {
		panic(err)
	}
	fmt.Println("redis connect")
}
